package com.scut.edu.wanyou.search;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.scut.edu.wanyou.R;
import com.scut.edu.wanyou.channel.Category;
import com.scut.edu.wanyou.channel.WanwanListActivity;
import com.scut.edu.wanyou.more.MoreActivity;
import com.scut.edu.wanyou.net.HttpTask;
import com.scut.edu.wanyou.net.WYParams;
import com.scut.edu.wanyou.util.Parser;
import com.scut.edu.wanyou.util.WYRequestListener;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class SearchActivity extends Activity implements OnClickListener{
	
    private ImageView act_search = null;
    private EditText act_search_edit = null;
    private ImageView act_refresh = null;
    
    private boolean isSearchEditShow = false;
    
    private ListView act_list = null;
    private ActListAdapter actListAdapter = null;
    
    private String TAG = "SearchActivity";
    
    public static List<Category> categories = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        prepareView();
        getCategories();
    }

    private void prepareView() {
        
        act_search = (ImageView)findViewById(R.id.act_search);
        act_search.setOnClickListener(this);
        
        act_search_edit =(EditText)findViewById(R.id.act_search_edit);
        
        act_refresh = (ImageView)findViewById(R.id.act_refresh);
        
    	act_list = (ListView)findViewById(R.id.m_act_list);
    	act_list.setOnItemClickListener(listener);
    }
    
    private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			Log.i(TAG, "OnItemClick: "+arg2);
			Intent intent = new Intent(SearchActivity.this,WanwanListActivity.class);
			intent.putExtra("cat_id", categories.get(arg2).getCat_id());
			startActivity(intent);
		}
	};
    
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0:
				findViewById(R.id.m_cat_progress).setVisibility(View.GONE);
				Bundle bundle = (Bundle)msg.obj;
				System.err.println(bundle.getString("info"));
				if(bundle.getString("flag").equals("ok"))
				{
					try {
						categories = Parser.getCatsFromJson(bundle.getString("cats"));
						actListAdapter = new ActListAdapter(categories);
						act_list.setAdapter(actListAdapter);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				break;
			case 1:
				
				break;
			default:
				break;
			}
			
		}
		
	};
	
	private WYRequestListener catRequestListener = new WYRequestListener() {
		
		@Override
		public void onException(Exception e) {
			// TODO Auto-generated method stub
			Log.i(TAG, "onException"+e.getMessage());
		}
		
		@Override
		public void onError(Error e) {
			// TODO Auto-generated method stub
			Log.i(TAG, "onError:"+e.getMessage());
		}
		
		@Override
		public void onComplete(Bundle bundle) {
			// TODO Auto-generated method stub
			handler.obtainMessage(0,bundle).sendToTarget();
		}
		
		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			Log.i(TAG, "onCancel");
		}

		@Override
		public void onStart() {
			// TODO Auto-generated method stub
			handler.obtainMessage(1).sendToTarget();
		}
	};
    
    private void getCategories()
    {
    	WYParams params = new WYParams();
		params.setAction("Http://125.216.245.70/wy/");
		params.add("action", "Cat_Get");
		new HttpTask(catRequestListener).execute(params);
    }
    
    
    private class ActListAdapter extends BaseAdapter
    {
    	
    	private List<Category> list = null;
    	
    	public ActListAdapter(List<Category> list)
    	{
    		this.list = list;
    	}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(arg1==null)
			{
				holder = new ViewHolder();
				arg1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.cat_list_item, null);
				holder.cat_slug = (TextView)arg1.findViewById(R.id.cat_slug);
				holder.cat_title = (TextView)arg1.findViewById(R.id.cat_title);
				holder.cat_logo = (ImageView)arg1.findViewById(R.id.cat_logo);
				arg1.setTag(holder);
			}else{
				holder = (ViewHolder)arg1.getTag();
			}
			
			holder.cat_title.setText(list.get(arg0).getCat_name());
			holder.cat_slug.setText(list.get(arg0).getSlug());
			
			try {
				holder.cat_logo.setImageBitmap(BitmapFactory.decodeStream(getResources().getAssets().open("cat_"+list.get(arg0).getCat_id()+".png")));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return arg1;
		}
		
		private class ViewHolder
		{
			public TextView cat_title;
			public TextView cat_slug;
			public ImageView cat_logo;
		}
    	
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		isSearchEditShow = true;
		act_search.setVisibility(View.GONE);
		act_search_edit.setVisibility(View.VISIBLE);
		act_search_edit.requestFocus();
		act_refresh.setVisibility(View.GONE);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if(isSearchEditShow)
		{
			act_search.setVisibility(View.VISIBLE);
			act_search_edit.setVisibility(View.GONE);
			act_refresh.setVisibility(View.VISIBLE);
			isSearchEditShow = false;
		}
		return super.dispatchKeyEvent(event);
	}


	
}
